library netutil;

use vh.sphynx.net.core.SphynxScriptNameResolver as SphynxScriptNameResolver;
use vh.sphynx.net.WebConnection as WebConnection;
use vh.sphynx.net.core.CacheManager as WebCacheManager;
use vh.sphynx.net.PasswordAuthenticator as PasswordAuthenticator;

const SEC_PER_DAY = 3600 * 24;
const SEC_PER_TEN_DAY = SEC_PER_DAY * 10;
const SEC_PER_MONTH = SEC_PER_DAY * 30;

var WebCacheFolder = struct {CacheFolder = "webcache", ArchiveFolder="webcache/archive"};
var DefaultWebCacheManager = createWebCacheManager();
var DefaultWebConnection = new WebConnection(DefaultWebCacheManager, null);
var DefaultAuthenticator = new PasswordAuthenticator();

function setPasswordAuthentication(username, password) {
	DefaultAuthenticator.setDefault(DefaultAuthenticator);
	DefaultAuthenticator.setAuthentication(username, password);
}

function createScriptNameResolver(func)
	SphynxScriptNameResolver.createNameResolver(__interpreter, __context, func)

function createWebCacheManager(cache="webcache", archive="webcache/archive")
	new WebCacheManager(cache, archive)
	
function download(url, expiredTimeSec=0-1, connection=DefaultWebConnection, timeout=10000, cacheFile='') {
	connection.setTimeout(timeout);
	connection.get(url, cacheFile, expiredTimeSec);
}
	
function setWebCacheFolder(name, cacheFolder="webcache", archiveFolder="webcache/archive") {
	WebCacheFolder.CacheFolder = cacheFolder + "/" + name;
	WebCacheFolder.ArchiveFolder = archiveFolder + "/" + name;
}

function setExpiredSecPeriod(sec, webcache=DefaultWebCacheManager)
	webcache.setCacheExpiredPeriod(sec)

function registerNameResolver(func, webcache=DefaultWebCacheManager)
	webcache.addCacheNameResolver(createScriptNameResolver(func))

	